package com.cn.txx.utils;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import com.cn.txx.entity.DBInfo;

import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.sql.Connection;

/**
 * 获取原生jdbc帮助类
 * @author Tu
 */
public class DBUtil {

	private static final Logger logger = Logger.getLogger(DBUtil.class);
	
	private static Connection getConn(String url,String username,String password,String driver){
		Connection conn = null;
	    try {
	        Class.forName(driver);
	        conn = DriverManager.getConnection(url, username, password);
	    } catch (Exception e) {
	      e.printStackTrace();
	    }
		
		return conn;
	}
	
	public static void closeDb(Connection conn,ResultSet rs, PreparedStatement ps){
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(ps != null){
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static Connection getConn(DBInfo dbInfo){
		return getConn(dbInfo.getUrl(),dbInfo.getUsername(),dbInfo.getPassword(),dbInfo.getDriver());
	}
	
	public static DBInfo getDBInfo(String dBname){
		Properties prop = new Properties();
		try {
			URL url = DBUtil.class.getResource("/jdbc.properties");
			prop.load(new FileInputStream(new File(url.getFile())));
		} catch (Exception e1) {
			logger.error("[读取jdbc配置文件错误----->] " + e1.getMessage());
			e1.printStackTrace();
		}
		DBInfo dbInfo = new DBInfo();
		dbInfo.setDriver(trim(prop.get(dBname+".driver")));
		dbInfo.setPassword(trim(prop.get(dBname+".password")));
		dbInfo.setUrl(trim(prop.get(dBname+".url")));
		dbInfo.setUsername(trim(prop.get(dBname+".username")));
		return dbInfo;
	}
	
	public static String trim(Object obj){
		if(!StringUtils.isEmpty(obj)){
			return obj.toString();
		}
		return null;
	}
}
